/**
 * @p.md
 * 
 * WasmPersistenceProvider 使用 WASM 桥接器与 Go 后端通信，提供持久化功能
 */
import { PersistenceProvider } from './persistenceProvider';
import { WasmBridge } from '../wasm/wasmBridge';

/**
 * WASM 持久化提供者，通过 WASM 桥与 Go 后端通信
 */
export class WasmPersistenceProvider implements PersistenceProvider {
  /**
   * 创建一个新的 WASM 持久化提供者
   * @param wasmBridge WASM 桥接器
   */
  constructor(private readonly wasmBridge: WasmBridge) {}
  
  /**
   * 获取指定持久化 ID 的事件
   * @param persistenceId 持久化 ID
   * @param fromIndex 开始索引（包含）
   * @param toIndex 结束索引（包含）
   * @returns 事件数组
   */
  async getEventsByPersistenceId(persistenceId: string, fromIndex: number, toIndex: number): Promise<any[]> {
    try {
      const result = await this.wasmBridge.invokeGoFunction(
        'GetEventsByPersistenceId',
        persistenceId,
        fromIndex,
        toIndex
      );
      
      if (typeof result === 'string') {
        return JSON.parse(result);
      }
      
      return result || [];
    } catch (error) {
      console.error('Error getting events from Go backend:', error);
      throw new Error(`Failed to get events: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 获取指定持久化 ID 的最新快照
   * @param persistenceId 持久化 ID
   * @returns 快照数据，如果不存在则返回 null
   */
  async getSnapshotByPersistenceId(persistenceId: string): Promise<any | null> {
    try {
      const result = await this.wasmBridge.invokeGoFunction(
        'GetSnapshotByPersistenceId',
        persistenceId
      );
      
      if (typeof result === 'string') {
        return JSON.parse(result);
      }
      
      return result || null;
    } catch (error) {
      console.error('Error getting snapshot from Go backend:', error);
      throw new Error(`Failed to get snapshot: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 持久化事件
   * @param persistenceId 持久化 ID
   * @param eventIndex 事件索引
   * @param event 事件数据
   */
  async persistEvent(persistenceId: string, eventIndex: number, event: any): Promise<void> {
    try {
      const serializedEvent = JSON.stringify(event);
      await this.wasmBridge.invokeGoFunction(
        'PersistEvent',
        persistenceId,
        eventIndex,
        serializedEvent
      );
    } catch (error) {
      console.error('Error persisting event to Go backend:', error);
      throw new Error(`Failed to persist event: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 持久化快照
   * @param persistenceId 持久化 ID
   * @param snapshotIndex 快照索引
   * @param snapshot 快照数据
   */
  async persistSnapshot(persistenceId: string, snapshotIndex: number, snapshot: any): Promise<void> {
    try {
      const serializedSnapshot = JSON.stringify(snapshot);
      await this.wasmBridge.invokeGoFunction(
        'PersistSnapshot',
        persistenceId,
        snapshotIndex,
        serializedSnapshot
      );
    } catch (error) {
      console.error('Error persisting snapshot to Go backend:', error);
      throw new Error(`Failed to persist snapshot: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除事件
   * @param persistenceId 持久化 ID
   * @param fromIndex 开始索引（包含）
   * @param toIndex 结束索引（包含）
   */
  async deleteEvents(persistenceId: string, fromIndex: number, toIndex: number): Promise<void> {
    try {
      await this.wasmBridge.invokeGoFunction(
        'DeleteEvents',
        persistenceId,
        fromIndex,
        toIndex
      );
    } catch (error) {
      console.error('Error deleting events from Go backend:', error);
      throw new Error(`Failed to delete events: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
  
  /**
   * 删除快照
   * @param persistenceId 持久化 ID
   * @param fromIndex 开始索引（包含）
   * @param toIndex 结束索引（包含）
   */
  async deleteSnapshots(persistenceId: string, fromIndex: number, toIndex: number): Promise<void> {
    try {
      await this.wasmBridge.invokeGoFunction(
        'DeleteSnapshots',
        persistenceId,
        fromIndex,
        toIndex
      );
    } catch (error) {
      console.error('Error deleting snapshots from Go backend:', error);
      throw new Error(`Failed to delete snapshots: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
} 